package com.liuwa.framework.aspectj;

import com.liuwa.common.annotation.TempUrl;
import com.liuwa.common.config.SysConfig;
import com.liuwa.common.constant.Constants;
import com.liuwa.common.exception.ParameterException;
import com.liuwa.common.utils.StringUtils;
import com.liuwa.common.utils.file.FileUploadUtils;
import com.liuwa.framework.config.ServerConfig;
import org.apache.commons.io.FileUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: TempUrlConvertAspect
 * @Author: Liuwa
 * @Description: 临时地址转换切面
 * @Date: 2022/5/10 19:45
 * @Version: 1.0
 */
@Order(2)
@Aspect
@Component
public class TempUrlConvertAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private ServerConfig serverConfig;

    //切点
    @Pointcut("@annotation(com.liuwa.common.annotation.TempUrlConvert)")
    public  void convertHandler() {}

    @Around("convertHandler()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        List<File> files = new ArrayList<File>();
        try{
            Object[] args = point.getArgs();
            for(Object obj : args){
                Class clazz = obj.getClass();

                for(Field field : clazz.getDeclaredFields()){
                    if(!field.isAnnotationPresent(TempUrl.class)){
                        continue;
                    }
                    TempUrl tempUrl = field.getAnnotation(TempUrl.class);
                    field.setAccessible(true);
                    String url = (String) field.get(obj);
                    if(StringUtils.isEmpty(url)){
                        continue;
                    }

                    String domain = serverConfig.getUrl();
                    if(!url.startsWith(domain) && !url.startsWith("/")){
                        continue;
                    }
                    url = url.replace(domain, "");

                    if(!url.startsWith(Constants.RESOURCE_PREFIX)){
                        continue;
                    }
                    url = url.replace(Constants.RESOURCE_PREFIX + "/", "");
                    if(!url.startsWith(SysConfig.TEMP_DIR)){
                        continue;
                    }
                    String fileName = url.replace(SysConfig.TEMP_DIR + "/", "");

                    File tempFile = FileUploadUtils.getAbsoluteFile(SysConfig.getTempPath(), fileName);
                    if(!tempFile.exists()){
                        throw new ParameterException(tempUrl.value() + "图片地址已失效，请重新上传");
                    }
                    File destFile = FileUploadUtils.getAbsoluteFile(SysConfig.getUploadPath(), fileName);
                    FileUtils.copyFile(tempFile, destFile);
                    files.add(destFile);
                    url = serverConfig.getUrl() + FileUploadUtils.getPathFileName(SysConfig.getUploadPath(), fileName);
                    field.set(obj, url);
                }
            }
            return point.proceed();
        }
        catch (Exception ex){
            logger.error(ex.getMessage(), ex);
            for(File file : files){
                file.delete();
            }
            throw ex;
        }

    }

}